<template>
    <div class="collection-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <div class="header-left">
                        <el-icon class="header-icon">
                            <Collection />
                        </el-icon>
                        <span>知识库管理</span>
                        <div class="search-box">
                            <el-input v-model="searchQuery" placeholder="请输入内容搜索" clearable @clear="handleSearch"
                                @keyup.enter="handleSearch">
                                <template #suffix>
                                    <el-icon class="search-icon" @click="handleSearch">
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                    </div>
                    <div class="header-right">
                        <el-button type="primary" @click="handleTest">
                            <el-icon>
                                <Connection />
                            </el-icon>测试命中情况
                        </el-button>
                        <el-button type="primary" @click="handleAdd">
                            <el-icon>
                                <Plus />
                            </el-icon>新增文档
                        </el-button>
                    </div>
                </div>
            </template>

            <el-table :data="collectionList" style="width: 100%" v-loading="loading" :header-cell-style="{
                background: '#f5f7fa',
                color: '#606266',
                fontWeight: 500
            }">
                <el-table-column prop="docId" label="ID" width="250" />
                <el-table-column prop="content" label="内容">
                    <template #default="{ row }">
                        <div class="content-preview">{{ getContentPreview(row.content) }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>编辑
                        </el-button>
                        <el-button type="danger" link @click="handleDelete(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[8, 10, 20, 50]" :total="total" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" background />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogType === 'add' ? '新增文档' : '编辑文档'" v-model="dialogVisible" width="600px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="内容" prop="content">
                    <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入文档内容" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitting">
                    确定
                </el-button>
            </template>
        </el-dialog>

        <!-- 测试对话框 -->
        <el-dialog title="测试命中情况" v-model="testDialogVisible" width="800px">
            <el-form ref="testFormRef" :model="testForm" :rules="testRules" label-width="120px">
                <el-form-item label="用户输入" prop="userInput">
                    <el-input v-model="testForm.userInput" type="textarea" :rows="4" placeholder="请输入测试内容" />
                </el-form-item>
                <el-form-item label="返回结果数量" prop="topK">
                    <el-input-number v-model="testForm.topK" :min="1" :max="100" />
                </el-form-item>
                <el-form-item label="相似度阈值" prop="threshold">
                    <el-input-number v-model="testForm.threshold" :min="0" :max="1" :precision="2" :step="0.1" />
                </el-form-item>
            </el-form>

            <div v-if="testResults.length > 0" class="test-results">
                <h3>测试结果：</h3>
                <el-table :data="testResults" style="width: 100%">
                    <el-table-column prop="docId" label="文档ID" width="250" />
                    <el-table-column prop="content" label="内容">
                        <template #default="{ row }">
                            <div class="content-preview">{{ getContentPreview(row.content) }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="score" label="相似度" width="120">
                        <template #default="{ row }">
                            {{ (row.score * 100).toFixed(2) }}%
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <template #footer>
                <el-button @click="testDialogVisible = false">关闭</el-button>
                <el-button type="primary" @click="handleTestSubmit" :loading="testing">
                    开始测试
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Collection, Search, Plus, Edit, Delete, Connection } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const collectionList = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const submitting = ref(false)

const form = ref({
    id: null,
    content: ''
})

const rules = {
    content: [
        { required: true, message: '请输入文档内容', trigger: 'blur' },
        { min: 1, message: '内容不能为空', trigger: 'blur' }
    ]
}

// 测试相关
const testDialogVisible = ref(false)
const testFormRef = ref(null)
const testing = ref(false)
const testResults = ref([])

const testForm = ref({
    userInput: '',
    topK: 5,
    threshold: 0.7
})

const testRules = {
    userInput: [
        { required: true, message: '请输入测试内容', trigger: 'blur' }
    ],
    topK: [
        { required: true, message: '请输入返回结果数量', trigger: 'blur' }
    ],
    threshold: [
        { required: true, message: '请输入相似度阈值', trigger: 'blur' }
    ]
}

// 获取知识库列表
const getCollectionList = async () => {
    loading.value = true
    try {
        const res = await request({
            url: '/collection/search',
            method: 'get',
            params: {
                pageNum: currentPage.value,
                pageSize: pageSize.value,
                keyword: searchQuery.value
            }
        })
        console.log('知识库列表数据:', res.data)
        collectionList.value = res.data.records
        total.value = res.data.total
    } catch (error) {
        console.error('获取知识库列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
    if (!dateTime) return ''
    const date = new Date(dateTime)
    return date.toLocaleString()
}

// 获取内容预览
const getContentPreview = (content) => {
    if (!content) return ''
    return content.length > 100 ? content.substring(0, 100) + '...' : content
}

// 新增文档
const handleAdd = () => {
    dialogType.value = 'add'
    form.value = {
        id: null,
        content: ''
    }
    dialogVisible.value = true
}

// 编辑文档
const handleEdit = (row) => {
    dialogType.value = 'edit'
    form.value = { ...row }
    dialogVisible.value = true
}

// 删除文档
const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该文档吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            await request({
                url: `/collection/${row.docId}`,
                method: 'delete'
            })
            ElMessage.success('删除成功')
            getCollectionList()
        } catch (error) {
            console.error('删除失败:', error)
        }
    })
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        submitting.value = true

        const url = dialogType.value === 'add' ? '/collection' : '/collection'
        await request({
            url,
            method: dialogType.value === 'add' ? 'post' : 'put',
            data: form.value
        })

        ElMessage.success(`${dialogType.value === 'add' ? '新增' : '编辑'}成功`)
        dialogVisible.value = false
        getCollectionList()
    } catch (error) {
        console.error('提交失败:', error)
    } finally {
        submitting.value = false
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getCollectionList()
}

// 分页相关
const handleSizeChange = (val) => {
    pageSize.value = val
    getCollectionList()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    getCollectionList()
}

// 打开测试对话框
const handleTest = () => {
    testForm.value = {
        userInput: '',
        topK: 5,
        threshold: 0.7
    }
    testResults.value = []
    testDialogVisible.value = true
}

// 提交测试
const handleTestSubmit = async () => {
    if (!testFormRef.value) return

    try {
        await testFormRef.value.validate()
        testing.value = true

        const res = await request({
            url: '/collection/test',
            method: 'get',
            params: testForm.value
        })
        testResults.value = res.data
    } catch (error) {
        console.error('测试失败:', error)
        ElMessage.error('测试失败')
    } finally {
        testing.value = false
    }
}

onMounted(() => {
    getCollectionList()
})
</script>

<style scoped>
.collection-container {
    padding: 20px;
    height: 100%;
}

.el-card {
    height: 100%;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 500;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 16px;
}

.header-icon {
    font-size: 18px;
    color: #409EFF;
}

.search-box {
    width: 250px;
    margin-left: 16px;
}

.search-icon {
    cursor: pointer;
    color: #606266;
}

.search-icon:hover {
    color: #409EFF;
}

.content-preview {
    white-space: pre-wrap;
    word-break: break-all;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-start;
}

:deep(.el-dialog__body) {
    padding-top: 20px;
}

.test-results {
    margin-top: 20px;
}

.test-results h3 {
    margin-bottom: 16px;
    color: #303133;
}
</style>